#include "unp.h"
#include "user.h"

void inform(struct user *u,int *group_fds,int *group_ids,int *maxi,fd_set *set,int flag )
{
	char tiptoself[MAXLINE],tip[MAXLINE];
	int i;
	int num;

	num = *maxi+1;
	
	//flag = 1:inform for coming
	//flag =-1:inform for leaving
	//flag = 0:inform for how many groups exitting
	//
	
	if(flag == 0)
	{
		//show all groups_ids
		if(num !=0)
		{
			snprintf(tiptoself,sizeof(tiptoself),"There are existing group,you can join a group or create a new group!\n");
			if(writen(u->socket,tiptoself,strlen(tiptoself))<0)
			{
				fprintf(stderr,"tip to self error");
			}
			for (i =0;i<num;i++)
			{		
					snprintf(tip,sizeof(tip)," %d\t",group_ids[i]);
					if(writen(u->socket,tip,strlen(tip))<0)
					{
						fprintf(stderr,"show groups_ids error");
					}
			
			}
		//	snprintf(tip,sizeof(tip),"\n\n");
		//	writen(u->socket,tip,strlen(tip));
		}
		
				
	}	
	else
	{
		for(i=0;i<num;i++)
		{
			if(group_fds[i]!=-1 && group_fds[i]!=u->socket && flag  ==1 && u->group_id == group_ids[i])
			{	
				snprintf(tiptoself,sizeof(tiptoself),"Now,everybody has known you ,let's communicate with others\n");
				if(writen(u->socket,tiptoself,strlen(tiptoself))<0)
				{
					fprintf(stderr,"tip to self error");

				}
				snprintf(tip,sizeof(tip),"%s has joined this group,let't greet  him!!\n",u->name);
				if(writen(group_fds[i],tip,strlen(tip))<0)
				{
					fprintf(stderr,"Write error to fd %d,Closing fd.\n",group_fds[i]);
					close(group_fds[i]);
					FD_CLR(group_fds[i],set);
					group_fds[i]=-1;
				}
			}

			if(group_fds[i]!=-1 && group_fds[i]!=u->socket && flag ==-1 && u->group_id == group_ids[i] )
			{
				snprintf(tip,sizeof(tip),"%s has left this group\n",u->name);
				if(writen(group_fds[i],tip,strlen(tip))<0)
				{
					close(group_fds[i]);
					FD_CLR(group_fds[i],set);
					group_fds[i]=-1;
				}			
			}
		}
	}
}
